package com.jiliang.common.security;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author YanShuang
 * @version v_1.0.1
 * @since 2022/3/18 13:41
 */
public class HMacDsUtil {

    public static String sha256_mac(String message, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
        return byteArrayToHexString(bytes);
    }

    public static String byteArrayToHexString(byte[] b) {
        StringBuilder sb = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                sb.append('0');
            sb.append(stmp);
        }
        return sb.toString().toLowerCase();
    }

}

